package com.edgar.plugin.hooks;

import android.app.Activity;
import android.app.Application;
import android.app.Instrumentation;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Bundle;

import com.edgar.plugin.PluginManager;
import com.edgar.plugin.pm.Plugin;
import com.edgar.plugin.utils.FieldUtils;

/**
 * Created by Edgar on 2018/2/11.
 */

public class HookInstrumentation extends Instrumentation {

    private static final String TAG = "HookInstrumentation";
    private Instrumentation mOriginInstrumentation;
    private PluginManager mPluginManager;

    public HookInstrumentation(Instrumentation instrumentation){
        mOriginInstrumentation = instrumentation;
        mPluginManager = PluginManager.getInstance();
    }

    @Override
    public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException,
            IllegalAccessException, ClassNotFoundException {
        return super.newActivity(cl, className, intent);
    }

    @Override
    public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return super.newApplication(cl, className, context);
    }

    @Override
    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        if (mPluginManager.isPlugin(activity.getIntent().getComponent())){
            Plugin plugin = PluginManager.getInstance().getPlugin(activity.getPackageName());
            FieldUtils.writeField(ContextWrapper.class,activity,"mBase",plugin.getPluginContext());
//            FieldUtils.writeField(ContextThemeWrapper.class,activity,"mResources",plugin.getResources());
//            final int themeResourceId = (int) FieldUtils.readField(ContextThemeWrapper.class,activity,"mThemeResource");
//            Resources.Theme theme = plugin.getTheme();
//            theme.setTo(activity.getTheme());
//            theme.applyStyle(themeResourceId,true);
//            FieldUtils.writeField(ContextThemeWrapper.class,activity,"mTheme",theme);
        }
        if (mOriginInstrumentation != null){
            mOriginInstrumentation.callActivityOnCreate(activity,icicle);
        } else {
            super.callActivityOnCreate(activity,icicle);
        }
    }
}
